package my.download;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import my.download.pojo.Download11;
import my.download.util.ExcelUtils;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.support.ClassicRequestBuilder;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Application14 {

    public static void main(String[] args) throws InterruptedException, IOException {

        JFrame jFrame = new JFrame();
        jFrame.setLayout(new FlowLayout());
        jFrame.setSize(500, 500);

        JLabel nameLabel = new JLabel("用户名：");
        JTextField nameField = new JTextField(40);
        jFrame.add(nameLabel);
        jFrame.add(nameField);

        JLabel pwdLabel = new JLabel("密码：");
        JTextField pwdField = new JTextField(40);
        jFrame.add(pwdLabel);
        jFrame.add(pwdField);

        JButton button = new JButton("开始下载");

        jFrame.add(button);

        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(e -> {
            jFrame.setVisible(false);
            log.info("下载开始：需要大概5-10分钟，请耐心等候！");
            String fileName = "导出-" + System.currentTimeMillis() + ".xlsx";
            String fullName = System.getProperty("user.dir") + "/" + fileName;
            boolean exc = download(fileName, fullName, nameField.getText(), pwdField.getText());
            if (exc) {
                log.info("下载完成，请打开文件：{}", fullName);
            } else {
                log.info("下载失败，请关闭窗口重试");
                try {
                    Thread.sleep(60 * 1000);
                } catch (InterruptedException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

    }

    private static boolean download(String fileName, String fullName, String name, String pwd) {
        Map<String, String> areaMap = getAreaMap();
        ObjectMapper objectMapper = new ObjectMapper();
        Path path = Paths.get(fullName);
        try (CloseableHttpClient httpclient = HttpClients.createDefault();
             OutputStream out = Files.newOutputStream(path)) {
            List<Download11> res = new ArrayList<>();
            ClassicHttpRequest loginRequest = ClassicRequestBuilder.post("https://server.xingeguanli.com/osapi/Login/Loginact")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                    .setEntity("{\"username\":\"" + name + "\",\"password\":\"" + pwd + "\"}", ContentType.APPLICATION_JSON)
                    .build();
            String respBody = httpclient.execute(loginRequest, response -> EntityUtils.toString(response.getEntity()));
            JsonNode jsonNode = objectMapper.readTree(respBody);
            String token = jsonNode.get("data").get("token").asText();
            for (int i = 1; i <= 10000; i++) {
                ClassicHttpRequest dataRequest = ClassicRequestBuilder.get("https://server.xingeguanli.com/osapi/Cases/casesGroup")
                        .addParameter("page", String.valueOf(i)).addParameter("perPage", "1000")
                        .addParameter("case_status", "0")
                        .addParameter("department_id", "7475")
                        .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36")
                        .addHeader("token", token).build();
                respBody = httpclient.execute(dataRequest, response -> EntityUtils.toString(response.getEntity()));
                jsonNode = objectMapper.readTree(respBody);
                JsonNode dataArray = jsonNode.get("data").get("data");
                if (dataArray == null || dataArray.size() <= 0) {
                    break;
                }
                for (JsonNode data : dataArray) {
                    String case_name = data.get("case_name").asText();
                    String case_phone = data.get("case_phone").asText();
                    String id = data.get("id").asText();
                    String contract = data.get("contract").asText();
                    String overdue_days = data.get("overdue_days").asText();
                    String case_idcard = data.get("case_idcard").asText();
                    String product_name = data.get("product_name").asText();
                    String loan_time = LocalDateTime.ofEpochSecond(data.get("loan_time").asLong(), 0, ZoneOffset.ofHours(8))
                            .format(DateTimeFormatter.ISO_LOCAL_DATE);
                    String case_area = data.get("case_area").asText();
                    String new_entrust_money = data.get("new_entrust_money").asText();
                    String last_capital = data.get("last_capital").asText();
                    String overdue_start_time = LocalDateTime.ofEpochSecond(data.get("overdue_start_time").asLong(), 0, ZoneOffset.ofHours(8))
                            .format(DateTimeFormatter.ISO_LOCAL_DATE);
                    String entrust_start = LocalDateTime.ofEpochSecond(data.get("entrust_start").asLong(), 0, ZoneOffset.ofHours(8))
                            .format(DateTimeFormatter.ISO_LOCAL_DATE);
                    String loan_money = data.get("loan_money").asText();

                    res.add(new Download11(case_name, case_phone, id, contract, overdue_days, case_idcard,
                            product_name, loan_time, case_area, new_entrust_money, last_capital, overdue_start_time, entrust_start, loan_money));
                }
                log.info("下载进度：{}%", i * 100 / jsonNode.get("data").get("pages").asInt());
            }
            String[][] headers = {
                    {"客户名称", "case_name"},
                    {"手机号", "case_phone"},
                    {"案件ID", "id"},
                    {"合同编号", "contract"},
                    {"逾期天数", "overdue_days"},
                    {"身份证号", "case_idcard"},
                    {"产品名称", "product_name"},
                    {"借款日期", "loan_time"},
                    {"户籍地址", "case_area"},
                    {"委托金额", "new_entrust_money"},
                    {"剩余本金", "last_capital"},
                    {"逾期开始时间", "overdue_start_time"},
                    {"委案日期", "entrust_start"},
                    {"贷款金额", "loan_money"},
            };
            ExcelUtils.exportExcel2007(fileName, headers, res, out);
            return true;
        } catch (Throwable e) {
            log.error("下载失败-", e);
            try {
                Files.deleteIfExists(path);
            } catch (IOException ignore) {}
            return false;
        }
    }

    public static Map<String, String> getAreaMap() {
        Map<String, String> areaMap = new HashMap<>();
        areaMap.put("11", "北京市");
        areaMap.put("12", "天津市");
        areaMap.put("13", "河北省");
        areaMap.put("14", "山西省");
        areaMap.put("15", "内蒙古自治区");
        areaMap.put("21", "辽宁省");
        areaMap.put("22", "吉林省");
        areaMap.put("23", "黑龙江省");
        areaMap.put("31", "上海市");
        areaMap.put("32", "江苏省");
        areaMap.put("33", "浙江省");
        areaMap.put("34", "安徽省");
        areaMap.put("35", "福建省");
        areaMap.put("36", "江西省");
        areaMap.put("37", "山东省");
        areaMap.put("41", "河南省");
        areaMap.put("42", "湖北省");
        areaMap.put("43", "湖南省");
        areaMap.put("44", "广东省");
        areaMap.put("45", "广西壮族自治区");
        areaMap.put("46", "海南省");
        areaMap.put("50", "重庆市");
        areaMap.put("51", "四川省");
        areaMap.put("52", "贵州省");
        areaMap.put("53", "云南省");
        areaMap.put("54", "西藏自治区");
        areaMap.put("61", "陕西省");
        areaMap.put("62", "甘肃省");
        areaMap.put("63", "青海省");
        areaMap.put("64", "宁夏回族自治区");
        areaMap.put("65", "新疆维吾尔自治区");
        areaMap.put("71", "台湾省");
        areaMap.put( "81", "香港特别行政区");
        areaMap.put("91", "澳门特别行政区");
        return areaMap;
    }
}
